import { useEffect } from "react";
import { socket, players } from "../../utils";
import Actor from "../actor";

export default () => {
  /*----------------------------变量声明-------------------------------*/
  /*----------------------------生命周期-------------------------------*/
  useEffect(() => {
    initSocket();
    return () => {
      players.clear();
    };
  }, []);

  // 绑定socket事件
  function initSocket() {
    if (socket) {
      socket.on("message", (data) => {
        const curPlayer = players.get(data.id);
        if (curPlayer) {
          const { velocity, jump } = data;
          curPlayer.velocity = velocity;
          curPlayer.jump = jump;
        } else {
          players.set(data.id, data);
        }
      });
      socket.on("off", (id) => {
        console.log("离线成员", id);
        players.delete(id);
      });
    }
  }
  console.log("players", players);
  /*----------------------------模型渲染-------------------------------*/
  return [...players.keys()].map((vo, index) => <Actor key={index} id={vo} />);
};
